package com.kingbook.services;

import com.alibaba.fastjson.JSONObject;
import com.kingbook.common.cache.JedisUtils;
import com.kingbook.common.utils.CollectionUtils;
import com.kingbook.common.utils.NumberUtils;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.auth.LoginManager;
import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Device;
import com.kingbook.entity.Master;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2019-12-18 21:37:35
 * @Version 1.0
 */
@Slf4j
@Service
public class MasterService extends SupportService {

    @Autowired
    DeviceService deviceService;

    @Autowired
    LoginService loginService;

    @Autowired
    PartnerService partnerService;

    @Autowired
    ConfigService configService;

    @Autowired
    SmsService smsService;

    @PostConstruct
    private void init() {
        setNamespace("Master");
    }

    public JSONResult sendVcode(Map<String, Object> param, String sign) {
        String phoneNo = MapUtils.getString(param, "phoneNo", "");
//        Device device = deviceService.queryDeviceBySign(sign);
//        if (device == null) {
//            log.info("---->签名不合法 sign:{} ", sign);
//            return JSONResult.failed("签名不合法");
//        }
        String vCode = NumberUtils.genNumber(4);
        log.info("---->发送验证码: {}  {} ", vCode, param);
        if (smsService.sendSmsAndCache(phoneNo, vCode))
            return JSONResult.success();
        return JSONResult.failed("发送验证码失败");
    }

    @Transactional
    public JSONResult doLoginPhone(Map<String, Object> param, String sign) {
        String phoneNo = MapUtils.getString(param, "phoneNo", "");
        String vCode = MapUtils.getString(param, "vCode", "");
        Device device = deviceService.queryDeviceBySign(sign);
//        if (device == null) {
//            log.info("---->签名不合法 sign:{} ", sign);
//            return JSONResult.failed("签名不合法");
//        }
        int devId = device != null ? device.getId() : 0;
        String value = JedisUtils.get("VCode:" + phoneNo);
        if (StringUtils.isEmpty(value)) {
            log.info("---->验证码过期 vCode:{} cache:{}", vCode, value);
            return JSONResult.failed("验证码过期");
        } else if (!vCode.equals(value)) {
            log.info("---->验证码错误 vCode:{} cache:{}", vCode, value);
            return JSONResult.failed("验证码错误");
        }

        Master master = byPhone(phoneNo);
        if (master != null) {
            log.info("--->用户已注册 mid:{} name:{} ", master.getId(), master.getName());
            param.put("id", master.getId());
            update("addLoginTimes", param);
            loginService.save(master.getId(), devId, sign);
            JSONResult re = LoginManager.doLogin(master.getId() + "", sign);
            if (re.isSuccess()) {
                JSONObject json = re.getData().getJSONObject(0);
                json.put("mid", master.getId());
                json.put("domainNameUrl", configService.queryDomainNameUrl());
            }
            return re;
        } else {
            int r = MapUtils.getIntValue(queryMap("maxCode", null)[0], "code", 2020);
            log.info("--->用户新注册 phoneNo:{} referralCode:{} ", phoneNo, r);
            param.put("referralCode", r);
            param.put("name", "金主"+r);
            param.put("phone1", phoneNo);
            JSONResult isMas = insertReturnKey("insert", param);
            int id = Integer.parseInt(isMas.getMsg());
            loginService.save(id, devId, sign);
            JSONResult re = LoginManager.doLogin(id + "", sign);
            if (re.isSuccess()) {
                JSONObject json = re.getData().getJSONObject(0);
                json.put("mid", id);
                json.put("domainNameUrl", configService.queryDomainNameUrl());
            }
            return re;
        }
    }

    @Transactional
    public JSONResult doLoginWx(Map<String, Object> param) {
        String sign = MapUtils.getString(param, "sign", "");
        String name = MapUtils.getString(param, "nickName", "");
        String unionId = MapUtils.getString(param, "unionId", "");
        Device device = deviceService.queryDeviceBySign(sign);
//        if (device == null) {
//            log.info("---->签名不合法 sign:{} ", sign);
//            return JSONResult.failed("签名不合法");
//        }
        int devId = device != null ? device.getId() : 0;
        Master master = byUnionId(unionId);
        if (master != null) {
            log.info("--->用户已注册 mid:{} name:{} ", master.getId(), master.getName());
            param.put("id", master.getId());
            update("addLoginTimes", param);
            loginService.save(master.getId(), devId, sign);
            JSONResult re = LoginManager.doLogin(master.getId() + "", sign);
            if (re.isSuccess()) {
                JSONObject json = re.getData().getJSONObject(0);
                json.put("mid", master.getId());
                json.put("domainNameUrl", configService.queryDomainNameUrl());
            }
            return re;
        } else {
            int r = MapUtils.getIntValue(queryMap("maxCode", null)[0], "code", 2020);
            log.info("--->用户新注册 name:{} referralCode:{} ", name, r);
            param.put("referralCode", r);
            param.put("name", name);
            JSONResult isMas = insertReturnKey("insert", param);
            int id = Integer.parseInt(isMas.getMsg());
            loginService.save(id, devId, sign);
            JSONResult re = LoginManager.doLogin(id + "", sign);
            if (re.isSuccess()) {
                JSONObject json = re.getData().getJSONObject(0);
                json.put("mid", id);
                json.put("domainNameUrl", configService.queryDomainNameUrl());
            }
            return re;
        }
    }

    public JSONResult modify(Map<String, Object> param) {
        JSONResult re = update("update", param);
        if (re.isSuccess() && re.getCount() > 0) {
            JSONResult p = partnerService.updatePartnerByRelatedId(param);
            if (!p.isSuccess()) {
                log.error("修改资料，同步更新伙伴资料错误:{} ", param);
            }
        }
        return re;
    }

    public JSONResult find(int id) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("id", id);
        return find("query", param);
    }

    public Master getById(int id) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("id", id);
        List<Master> master = queryList("query", param, Master.class);
        if (CollectionUtils.isNotEmpty(master)) {
            return master.get(0);
        }
        return null;
    }

    private Master byUnionId(String unionId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("unionId", unionId);
        List<Master> master = queryList("query", param, Master.class);
        if (CollectionUtils.isNotEmpty(master)) {
            return master.get(0);
        }
        return null;
    }

    private Master byPhone(String phone) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("phone1", phone);
        List<Master> master = queryList("query", param, Master.class);
        if (CollectionUtils.isNotEmpty(master)) {
            return master.get(0);
        }
        return null;
    }

    public JSONResult confirmPartner(Map<String, Object> param, int mid) {
        param.put("mid", mid);
        return query("queryRelatedMaster", param);
    }

}
